/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true, jquery:true, indent:4, maxerr:50 */
(function(window, document, $, undefined ){
var $canvas;
var survolMiniMap = false;

var wrapWidth;
var wrapHeight;
var debordX;
var debordY;

//Navigation Canvas
var canvasNavigation = function(){
		var $dragger = $("#dragger");
		
		adapteMap()
							
		$canvas.draggable({containment: 'parent',drag:function(event, ui){
			var posLeft=-(parseFloat($canvas.css('left'))-debordX)/20+"px";
			var posTop=-(parseFloat($canvas.css('top'))-debordY)/20+"px";
			$dragger.css({'left': posLeft, 'top':posTop});
		}});


	   $dragger.draggable({containment: 'parent',drag:function(event, ui) {
			var posLeft=-parseFloat($dragger.css('left'))*20+debordX+"px";
			var posTop=-parseFloat($dragger.css('top'))*20+debordY+"px";
			$canvas.css({'left': posLeft, 'top':posTop});

	   }});
		//Navigation au clic Minimap
				
					
	   $("#minimap").mouseover(function(){
						survolMiniMap = true;
					});
	   $("#minimap").mouseout(function(){
						survolMiniMap = false;
					});
	   $("#minimap").click(function(e){
					  
		if(survolMiniMap == true)
					  
						{
						
								var draggerLocation = $("#dragger").offset();
								var relativeX = e.pageX;
								var relativeY = e.pageY;
								var shift_left = relativeX - draggerLocation.left;
								var shift_top = relativeY - draggerLocation.top;						

								$("#dragger").animate({
									  'top': "+="+shift_top+(-20)+"px",
									  'left': "+="+shift_left+(-20)+"px"
								},300);
								
								$('#canvas').animate({
									  'top':  "+="+shift_top*-20+"px",
									  'left': "+="+shift_left*-20+"px"
								}, 300);								
							 
						}

		});	
					//FIN
};
// adapte map et minimap aux dimension de la fenetre
function adapteMap(){
	wrapWidth = parseFloat($("#wrap-canvas").css("width"));
	wrapHeight = parseFloat($("#wrap-canvas").css("height"));
	
	debordX = 4000 - wrapWidth;
	debordY = 3000 - wrapHeight;
	
	$("#bigcanvas").css("width", ((4000 - wrapWidth)*2)+wrapWidth+"px");
	$("#bigcanvas").css("height", ((3000 - wrapHeight)*2)+wrapHeight+"px");
	$("#bigcanvas").css("left", -debordX +"px");
	$("#bigcanvas").css("top", -debordY +"px");
		
	$("#dragger").css("width",((wrapWidth/20))-2+"px");
	$("#dragger").css("height",((wrapHeight/20))-2+"px");
	
	var $dragger = $("#dragger");
	
	var posLeft=-(parseFloat($canvas.css('left'))-debordX)/20+"px";
	var posTop=-(parseFloat($canvas.css('top'))-debordY)/20+"px";
	$dragger.css({'left': posLeft, 'top':posTop});
	if(parseFloat($dragger.css("left")) < 0){
			$dragger.css("left", "0px");
	}
	
	var posLeft=-parseFloat($dragger.css('left'))*20+debordX+"px";
	var posTop=-parseFloat($dragger.css('top'))*20+debordY+"px";
	$canvas.css({'left': posLeft, 'top':posTop});
}
//Controls #btnSendArtWork button
var sendArtWork = function(){
	var btnSendArtWork = $('#bt-send-work');
	
	btnSendArtWork.click(function(e){
		e.preventDefault();
		hideMenu(true);
		setCanvas.enable(); 			
	});
};
//Allow Canvas to receive an object
var setCanvas = {
	enable: function(){
		$canvas.addClass('crosshair');
		
		//calculate mouse position
		$canvas.click(function(ev){
			var $this = $(this), 
				tPos = $this.offset(), 
				mouseX = ev.pageX, 
				mouseY = ev.pageY;

		    mouseX -= tPos.left + parseInt($this.css('paddingLeft')) + parseInt($this.css('borderLeftWidth'));
		    mouseY -= tPos.top + parseInt($this.css('paddingTop')) + parseInt($this.css('borderTopWidth'));
			
			collection.save(mouseX, mouseY);
			setCanvas.disable();
		});		
		
		return true;
	},
	disable: function(){
		/* 1. desactivate function collection.save(); 2. toggleclass '.crosshair'*/
		$canvas.removeAttr('class').unbind('click');
		return false;
	}
};
//Function: show lightbox to upload object
var uploadObject = function(mouseX, mouseY){
	var $categoryitens = $('#category li');
	var	category_selected, media_type;
	
        // Chargement de la vue permettant l'upload de fichiers
        $.ajax({
                type: "POST",
                url: "../upload/index",
                //cache: false,
                async: false,
                success: function(msg) {

                    $('#popup').html(msg);
                    $('#popup').fadeIn(1000);
                    $('#overlay_page').fadeIn(800);
                }
        });


        // Soumission du formulaire
	$("#form-upload").submit(function(){

            // On récupère le nom du fichier
            var file_name = ($('#userfile').val());

            // Appel à la méthode du fichier 'ajaxfileupload.js' autorisant l'uplpoad de fichiers
            $.ajaxFileUpload({
                type:          'POST',
                url:           '../upload/do_upload',
                secureuri:      false,
                fileElementId: 'userfile',
                async: false,
                dataType    : 'json',
                data: {userfile: file_name, oeuvres_locX: mouseX, oeuvres_locY: mouseY, pensee_nom: category_selected},
                success: function(data) {

                    //alert(data.status);

                    if(data.status != 'error'){

                        // Modification de propriétés CSS
                        $('#popup').css('display','none');
                        $('#overlay_page').css('display','none');

                        // Affichage dans le div de callback le message issu du contrôleur
                        $('#controller_callback').html(data.msg);

                        // Apparition progressive de la vue du callback, suivie d'une disparition progressive
                        $('#controller_callback').fadeIn(500, function(){
                            $('#controller_callback').fadeOut(10000);
                        });

                        // Récupération des données transmises en JSON
                        media_type = data.oeuvre_type;
                        id = data.oeuvre_id;
                        url = data.oeuvre_fichier;

                        // Ajout des bonnes classes à l'oeuvre nouvellement uploadée
                        classes = category_selected + media_type;
                        $('.work.init').attr('id', id).addClass(classes).removeClass('init');
                        collection.addInfo($(id), url);
                    }

                    else{
                        // .../... RAF
                        
                        // Modification de propriétés CSS
                        $('#popup').css('display','none');
                        $('#overlay_page').css('display','none');

                        // Affichage dans le div de callback le message issu du contrôleur
                        //$('#controller_callback').html(data.msg);
                        

                        // Apparition progressive de la vue du callback, suivie d'une disparition progressive
                        /*$('#controller_callback').fadeIn(500, function(){
                            $('#controller_callback').fadeOut(10000);
                        });*/
                        
                        //Gabriela : supprimer le div du marqueur indiquant l'emplacement de l'oeuvre qui aurait dû être déposée
                        //$('.work.init').empty().remove();
                    }

                },
                error: function(data) {
                    
                    $('#popup').css('display','none');
                    $('#overlay_page').css('display','none');
                    //alert(data.responseText);
                }

            });

            // En écrivant 'return false', on ne renvoie pas le formulaire dans la vue! très important
            return false;
	});

        // Requête AJAX d'enregistrement d'un nouveau collage
        $('#bt-cancel').click(function(){
            $('#popup').css('display','none');
            $('#popup').html('');
            $('#overlay_page').css('display','none');
            
            //$('.work.init').empty().remove();
            //Gabriela : supprimer le div du marqueur indiquant l'emplacement de l'oeuvre qui aurait dû être déposée
        });

	$categoryitens.live('click',function(){
		$('#category li.selected').removeClass('selected');
		$(this).addClass('selected');
		category_selected = $('#category li.selected').attr('class');
		category_selected = category_selected.replace('selected','');
		
		return category_selected;
	})
};
//Hides menu when sending an object
var hideMenu = function(isSendingObject){
	var $menuitens = $('#menu li'),
		$itenstext = $menuitens.find('a');
	
	/*
	*@bug: bind/unbind events
	*/
	
	if(isSendingObject){
		$menuitens.removeClass('active');//.off('click mouseenter mouseleave');
		$itenstext.slideUp('slow');
	}else{
		$menuitens.addClass('active');//.on('click onmouseenter onmouseleave');
		$itenstext.slideDown('slow');
	}
			
};
//Fold/Unfolding menu
var foldMenu = function(){
	$('#menu li').mouseenter(function(){
		$(this).animate({
		    'padding-top': '19px'
		  }, 300);

	}).mouseleave(function(){
		$(this).animate({
		    'padding-top': '0'
		 }, 300);
		
	}).click(function(e){
		$(this).toggleClass('active');
		e.preventDefault();
		navFilter();
	});
};
//Filter: Show elements on canvas depends on activeted menu 
var navFilter = function(){
	$itensmenu = $('#menu li');
	
	$itensmenu.not('.active').each(function(){
		var classe = $(this).attr('class');
		classe = classe.replace(' active','');
		classe = '.'+classe;
		$canvas.find(classe).fadeOut('slow');
	});	
	
	$('#menu li.active').each(function(){
		var classe = $(this).attr('class');
		classe = classe.replace(' active','');
		classe = '.'+classe;
		$canvas.find(classe).fadeIn('slow');
	});	
};

////Preview object
var previewObject = function(type){

    if(type==='image'){
       $('.preview').fancybox({
            'autoDimensions'     :true,
            'transitionIn'          : 'fade',
            'transitionOut'         : 'fade',
            'speedIn'		  : 600, 
            'speedOut'		  : 200,
            'type'                  :'image'
	});
        
    }else{
	$('.preview').fancybox({ 
            'autoDimensions'     :true,
            'transitionIn'  : 'fade',
            'transitionOut' : 'fade',
            'speedIn'	: 600, 
            'speedOut'	: 200,
            'type'          :'iframe'
         });
   }
   
   
};


//Object - create elements
var collection = {
	create: function(id, mouseX, mouseY, pensee, type, url, newobj){		
		mouseX = mouseX || 0;
		mouseY = mouseY || 0;			
	
		var classes =  'work oeuvres_draggable '+ pensee + ' ' + type;
		
		// var url_original = 'http://farm5.static.flickr.com/4058/4252054277_f0fa91e026_m.jpg';
		//Verifier le type de media pour avoir la bonne fancybox
		if(type==="video"){
			url_original = "../../oeuvres/originaux/"+url;
		}else{
			url_original = "../../oeuvres/originaux/"+url;
		}
		
		
			
		//create element
		var workLink = document.createElement('a');
//		workLink.setAttribute('id',id);		
		workLink.setAttribute('class', 'preview');
		workLink.setAttribute('href', url_original);
                
                
		
		var oWork = document.createElement('div');
		oWork.setAttribute('id',id);		
		oWork.setAttribute('class', classes);
                
              
		
		document.getElementById('canvas').appendChild(workLink);
		workLink.appendChild(oWork);
		
		collection.position(oWork, mouseX, mouseY, newobj);
		collection.addInfo(oWork, url);	
		
                     //              Preview d'un objet
                $(oWork).click(function(){
                 previewObject(type)
 
                });
	},
 
 
        
	position: function(oWork, mouseX, mouseY, newobj){ 
		mouseX = mouseX || 0;
		mouseY = mouseY || 0;
		oWork = $(oWork);
		
		mouseY = mouseY+"px";
		mouseX = mouseX+"px";

		oWork.css({top:mouseY, left:mouseX});

		//animation and callBack
		oWork.fadeIn('slow',function(){
			setCanvas.disable();
			if(newobj){
				mouseY = parseInt(mouseY);
				mouseX = parseInt(mouseX)
				uploadObject(mouseX, mouseY);
			}
		});


	},
	addInfo: function(oWork, url){
		oWork = $(oWork);		
                
                var url_new = url.substr(0,url.length-3);
                console.log(url.substr(url.length-3));
                var html = '';
                if(url.substr(url.length-3)!='jpg'){
                    html = '<div class="info"><img src="../../oeuvres/vignettes/'+ url_new +'png"></div>';
                }
                else{
                    html = '<div class="info"><img src="../../oeuvres/vignettes/'+ url +'></div>';
                }
		oWork.append(html);
	},
	toggleInfo: function(){
		var $work = $('.work'),
			$info = $('.info');				
		
		//show/hide vignette
		$work.mouseenter(function(){
			$(this).find($info).css('display','block');//fadeIn(100);
		}).mouseleave(function(){
			$(this).find($info).css('display','none');//fadeOut(100);
		});	
				
	},
	save: function(mouseX, mouseY){	
		var isPositionAllowed = true,
		oCollection = $('.work');

		/*
			verify if there is already an object in the same position
			@todo : calculate object area and safety area;
			1. True: send a error message;
			2. False: positioning 
		*/
		
		oCollection.each(function(){
			var posX = parseInt($(this).css('left'),10),
			posY = parseInt($(this).css('top'),10),
			radius = 15;

			if((posX === mouseX) && (posY === mouseY)){
				//@todo MESSAGE: 'sorry, u cant position this object here';
				isPositionAllowed = false;
			}
		});			

		//IF #canvas can be edited and this object isn't in the same position as another one THAN create a new object
		if(setCanvas && isPositionAllowed){
			//@todo: get values from popup
			pensee = 'init';
			type = "";
			id = "";
			url = "";
			
			collection.create(id, mouseX, mouseY, pensee, type, url, true)
		}

	}
};


//Get objects that already exist and create those elements.		
$.getJSON('getData', function(data){

        //console.log(data.collection);
        if(data.collection != null){
            $.each(data.collection, function(){
                collection.create(this.oeuvres_id, this.oeuvres_locX, this.oeuvres_locY, this.pensees_nom, this.types_nom, this.oeuvres_fichier,  false);
            });
            collection.toggleInfo();
        }
	
	
	//Filtre d'elements sur la page
	navFilter();	

});


/*****************
* Document ready *
******************/
$(document).ready(function(){

	$canvas = $('#canvas');
	
	//Comportement du menu
	foldMenu();
	
	// Depot d'une oeuvre
	sendArtWork();
	
	//Navigation dans le Canvas
	canvasNavigation();
	

	
});


})(this, this.document, jQuery);
